package training.model;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import training.entity.User;
import training.util.HibernateUtil;

public class UserDAO {
	
	private SessionFactory sessionFactory = null;
	
	public UserDAO() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllUser() {
		Session session = sessionFactory.openSession();
		List<User> result = session.createQuery("from User").list();
		session.close();
		return result;
	}
	
	public User getUser(String account) {
		Session session = sessionFactory.openSession();
		User user = (User) session.createQuery("from User u where u.account='" + account + "'").uniqueResult();
		session.close();
		return user;
	}
	
	public void addUser(User user) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.save(user);
		transaction.commit();
		session.close();
	}
	
	public void removeUser(User user) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.delete(user);
		transaction.commit();
		session.close();
	}
	
	public void updateUser(User user) {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		session.update(user);
		transaction.commit();
		session.close();	
	}
}
